package it.cpyx.appengine.server.data.utils;

import it.cpyx.appengine.server.data.LabelData;
import it.cpyx.appengine.server.data.PMF;

import java.util.List;

import javax.jdo.JDOObjectNotFoundException;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;

public class LabelDataUtils {
	
	public static Long addTextDataToLabelDataIfNotExist(String urlExtension,Long textDataId){
		Long i=null;
		if(getByUrlExtension(urlExtension)==null){
			Long id=insert(urlExtension);
			i=addTextDataToLabelData(textDataId, id);
		}else{
			i=addTextDataToLabelData(textDataId, getByUrlExtension(urlExtension).getId());
		}
		return i;
	}
	
	public static Long addTextDataToLabelData(Long textDataId,Long labelDataId){
		LabelData l=getById(labelDataId);		
		l.addTextDataList(textDataId);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Long id=pm.makePersistent(l).getId();
		pm.close();
		return id;
	}
	
	public static LabelData getById(Long id){		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		LabelData l=null;
    	try {
    		l = pm.getObjectById(LabelData.class, id);
    	} catch (JDOObjectNotFoundException e) {
    		
    	} finally {
    		pm.close();
    	}
    	return l;
	}
	
	public static LabelData getByUrlExtension(String urlExtension){		
		PersistenceManager pm = PMF.get().getPersistenceManager();
		LabelData l=null;
    	Query query = pm.newQuery(LabelData.class);
		query.declareParameters("java.lang.String urltxt");
		query.setFilter("urlExtension == urltxt");
		List<LabelData> results = (List<LabelData>)query.execute(urlExtension);
	    List<LabelData> LabelList=results;
	    for(LabelData l2:LabelList){
	    	l=l2;
	    }
	    pm.close();
    	return l;
	}
	
	public static Long insert(String urlExtension){
		LabelData labelData=new LabelData(urlExtension);
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Long id=pm.makePersistent(labelData).getId();
		pm.close();
		return id;
	}
}
